// Copyright  2004-2008 Backplane Ltd.
//
// This file is part of Ubiquity formsPlayer
//
// Ubiquity formsPlayer is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
//
// Ubiquity formsPlayer is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License
// along with Ubiquity formsPlayer If not, see <http://www.gnu.org/licenses/>.
//	
//
//   Purpose: implementation of GetEnclosingBindingOf.
//   $Id$


#include "stdafx.h"
#include "nodebinding.h"
#include "GetEnclosingBindingOf.h"
#include "XFormsElement.h"
#include "Model.h"

HRESULT GetEnclosingBindingOf(CImpl * pEnclosed,CImplNodeBinding ** ppEnclosing,CImplModel ** ppModel)
{
	HRESULT hr = S_FALSE;
	CImpl * pParent = pEnclosed->m_pParentImpl;
	CImpl * pNext = 0;
	// While we have a parent and it not a CImplNodeBinding
	// as we can get context from a CImplNodeBinding object

	while(pParent)
	{
		CImplNodeBinding * pParentAsNB = dynamic_cast<CImplNodeBinding*>(pParent);
		
		if(pParentAsNB)
		{
			*ppEnclosing = pParentAsNB;
			break;
		}
		else
		{
			CImplModel * pParentAsModel = dynamic_cast<CImplModel*>(pParent);
			if(pParentAsModel)
			{
				*ppModel = pParentAsModel;
				break;
			}
		}

		pNext = pParent->m_pParentImpl;
		// If the next parent is null then as long as it has a 
		// Behaviour when resolves it parent by crawling the HTML tree.
		if(!pNext) 
		{
			if(pParent->m_pXFormsElement) 
			{
				pParent->m_pXFormsElement->ResolveEnclosingBinding();
				pNext = pParent->m_pParentImpl;
			}
		}
		else
		{
			*ppModel = dynamic_cast<CImplModel*>(pNext);
			if(*ppModel)
			{
				pParent = 0;
				break;
			}
		}
		// Set the next parent to the current
		pParent = pNext;
	}

	// Before setting the Context Parent we must confirm that
	// it is a valid pointer i.e. is a CImplNodeBinding.
	
	if(*ppEnclosing || *ppModel) {
		hr = S_OK;
	}
	return hr;
}
